import subprocess
import os
import requests
import threading

cookies = {
    'UPLUS_ULSESSION': 'y9I_kvWpFikQmWmBQbQKNoHCvRhYjfwPH6rOkJueiAgiCbxYPLFNENQ8fB15Kcea4BTgh3vZnlQomzOKDyV5LA-OqAVAdcOLw-8cBEMG8RTBMgAkf_y9xWm_Nw3FLZ9xOmZEuGNP_pJLZHHh2G1Y0-obOQ06Z0hNNvUkXZbdFko',
}

headers = {
    'Accept': '*/*',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
    # 'Cookie': 'UPLUS_ULSESSION=y9I_kvWpFikQmWmBQbQKNoHCvRhYjfwPH6rOkJueiAgiCbxYPLFNENQ8fB15Kcea4BTgh3vZnlQomzOKDyV5LA-OqAVAdcOLw-8cBEMG8RTBMgAkf_y9xWm_Nw3FLZ9xOmZEuGNP_pJLZHHh2G1Y0-obOQ06Z0hNNvUkXZbdFko',
    'Origin': 'https://www.hs.net',
    'Referer': 'https://www.hs.net/',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'cross-site',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
    'sec-ch-ua': '"Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Linux"',
}

url='https://uplus.hundsun.com/ulv/BE3AEB52AB675D878C6B1E1FFC9918F9/10342_20211118145701.m3u8?ultk=UPLUS-3f458372c1f04b59b0452287aae15d12'

response = requests.get(
    url,
    cookies=cookies,
    headers=headers,
)
#print(response.text);
i=url.rindex('/')
path=url[0:i]
print(path)
destPath="/u2/data/m3u8/"
dd = path[path.rindex("/") + 1:]
#print(dd)
destPath=destPath+dd+"/"
os.makedirs(destPath)

with open(destPath + "a.m3u8", "wb") as code:
    code.write(response.content)

semaphore = threading.BoundedSemaphore(5)
def download(a):
    semaphore.acquire()
    uu = path + "/" + a
    print(uu)
    r = requests.get(uu,
                     cookies=cookies,
                     headers=headers,
                    )
    with open(destPath + a, "wb") as code:
        code.write(r.content)
    semaphore.release()
tr=[]
for a in response.text.splitlines():
    if "#EXT" not in a:
        t = threading.Thread(target=download, args=(a,))
        t.start()
        tr+=[t]
print("-"*40)
for t in tr:
    t.join();
print("*" * 40)

# p = subprocess.Popen('curl -s  https://www.sina.com.cn|grep  "新闻"', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# for line in p.stdout.readlines():
#     pass
    #print(line.decode("utf-8"))